/* eslint-disable */
const {
  Connection,
  Keypair,
  PublicKey,
  LAMPORTS_PER_SOL,
} = require('@solana/web3.js');
const axios = require('axios');
const bs58 = require('bs58').default || requi  // 5. 获取初始代币信息
  console.log(`\n📊 获取代币初始信息...`);('bs58');
const fs = require('fs');

// 配置
const DEVNET_RPC = 'https://api.devnet.solana.com';
const BACKEND_API = 'http://localhost:7172/api';

// 指定的钱包地址
const CREATOR_WALLET = '6XjguvTFi8nWhZEfmYYFYW53bUXPkdEcRJ9AemhA1vVR'; // 创建者钱包
const BUYER_WALLET = 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac'; // 购买者钱包

/**
 * 加载指定钱包
 */
function loadWalletByAddress(targetAddress) {
  try {
    // 检查是否是默认 Solana CLI 钱包
    if (targetAddress === 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac') {
      try {
        const defaultWallet = require('os').homedir() + '/.config/solana/id.json';
        const walletData = JSON.parse(fs.readFileSync(defaultWallet, 'utf8'));
        const keypair = Keypair.fromSecretKey(new Uint8Array(walletData));
        console.log(`✅ 使用 Solana CLI 默认钱包: ${targetAddress}`);
        return keypair;
      } catch (e) {
        console.log(`❌ 无法加载 Solana CLI 钱包: ${e.message}`);
      }
    }
    
    // 检查是否是创建者钱包，从 frontend/buyer-wallet.json 加载
    if (targetAddress === '6XjguvTFi8nWhZEfmYYFYW53bUXPkdEcRJ9AemhA1vVR') {
      try {
        const buyerWalletPath = '../frontend/buyer-wallet.json';
        const walletData = JSON.parse(fs.readFileSync(buyerWalletPath, 'utf8'));
        if (walletData.publicKey === targetAddress && walletData.secretKey) {
          console.log(`✅ 在 buyer-wallet.json 中找到创建者钱包: ${targetAddress}`);
          return Keypair.fromSecretKey(new Uint8Array(walletData.secretKey));
        }
      } catch (e) {
        console.log(`❌ 无法加载 buyer-wallet.json: ${e.message}`);
      }
    }
    
    // 首先尝试从 test-addresses.json 查找
    const testAddresses = JSON.parse(fs.readFileSync('./test-addresses.json', 'utf8'));
    const wallet = testAddresses.find(w => w.publicKey === targetAddress);
    if (wallet) {
      console.log(`✅ 在 test-addresses.json 中找到指定钱包: ${targetAddress}`);
      return Keypair.fromSecretKey(new Uint8Array(wallet.secretKey));
    }
    
    // 尝试从其他钱包文件查找
    const walletFiles = fs.readdirSync('.').filter(f => f.endsWith('.json') && f.includes('wallet'));
    for (const file of walletFiles) {
      try {
        const walletData = JSON.parse(fs.readFileSync(file, 'utf8'));
        if (Array.isArray(walletData)) {
          // 私钥数组格式
          const keypair = Keypair.fromSecretKey(new Uint8Array(walletData));
          if (keypair.publicKey.toString() === targetAddress) {
            console.log(`✅ 在 ${file} 中找到指定钱包: ${targetAddress}`);
            return keypair;
          }
        } else if (walletData.publicKey === targetAddress && walletData.secretKey) {
          // 对象格式
          console.log(`✅ 在 ${file} 中找到指定钱包: ${targetAddress}`);
          return Keypair.fromSecretKey(new Uint8Array(walletData.secretKey));
        }
      } catch (e) {
        // 忽略无法解析的文件
      }
    }
    
    console.log(`❌ 未找到钱包 ${targetAddress} 的私钥，将生成新钱包用于测试`);
    return Keypair.generate();
  } catch (error) {
    console.log(`⚠️  加载钱包失败: ${error.message}，使用生成的钱包`);
    return Keypair.generate();
  }
}

/**
 * 通过后端API创建代币
 */
async function createTokenViaAPI(creatorKeypair, tokenConfig) {
  console.log(`🚀 创建代币: ${tokenConfig.symbol}`);
  
  try {
    const response = await axios.post(`${BACKEND_API}/bonding-curve/create-token`, {
      name: tokenConfig.name,
      symbol: tokenConfig.symbol,
      uri: tokenConfig.uri,
      creatorPrivateKey: bs58.encode(creatorKeypair.secretKey)
    });
    
    if (response.data.success) {
      console.log(`✅ 代币创建成功: ${response.data.data.tokenMint}`);
      return {
        mint: response.data.data.tokenMint,
        transaction: response.data.data.transaction
      };
    } else {
      throw new Error(response.data.error);
    }
  } catch (error) {
    console.error(`❌ 代币创建失败:`, error.response?.data || error.message);
    return null;
  }
}

/**
 * 购买代币（执行真实交易）
 */
async function buyTokens(tokenMint, buyerKeypair, solAmount) {
  console.log(`💰 购买代币: ${solAmount} SOL`);
  
  try {
    // 首先获取交易
    const response = await axios.post(`${BACKEND_API}/bonding-curve/buy`, {
      tokenMint: tokenMint,
      solAmount: solAmount,
      buyerPublicKey: buyerKeypair.publicKey.toString()
    });
    
    if (!response.data.success) {
      throw new Error(response.data.error);
    }
    
    // 反序列化交易
    const {Connection, Transaction, Keypair} = require('@solana/web3.js');
    const connection = new Connection(DEVNET_RPC, 'confirmed');
    
    const serializedTx = Buffer.from(response.data.data.transaction, 'base64');
    const transaction = Transaction.from(serializedTx);
    
    // 签名并发送交易
    transaction.sign(buyerKeypair);
    const signature = await connection.sendTransaction(transaction, [buyerKeypair]);
    
    // 等待确认
    await connection.confirmTransaction(signature);
    
    console.log(`✅ 购买成功！交易: ${signature}`);
    return { transaction: signature };
    
  } catch (error) {
    console.error(`❌ 购买失败:`, error.response?.data || error.message);
    return null;
  }
}

/**
 * 获取代币价格
 */
async function getTokenPrice(tokenMint) {
  try {
    const response = await axios.get(`${BACKEND_API}/bonding-curve/price/${tokenMint}`);
    
    if (response.data.success) {
      return response.data.data;
    } else {
      throw new Error(response.data.error);
    }
  } catch (error) {
    console.error(`❌ 获取价格失败:`, error.response?.data || error.message);
    return null;
  }
}

/**
 * 获取代币信息
 */
async function getTokenInfo(tokenMint) {
  try {
    const response = await axios.get(`${BACKEND_API}/bonding-curve/info/${tokenMint}`);
    
    if (response.data.success) {
      return response.data.data;
    } else {
      throw new Error(response.data.error);
    }
  } catch (error) {
    console.error(`❌ 获取代币信息失败:`, error.response?.data || error.message);
    return null;
  }
}

/**
 * 检查钱包余额
 */
async function checkWalletBalance(publicKey, label) {
  try {
    const connection = new Connection(DEVNET_RPC, 'confirmed');
    const balance = await connection.getBalance(new PublicKey(publicKey));
    const solBalance = balance / LAMPORTS_PER_SOL;
    console.log(`💰 ${label} SOL余额: ${solBalance.toFixed(6)} SOL`);
    return solBalance;
  } catch (error) {
    console.error(`❌ 检查${label}余额失败:`, error.message);
    return 0;
  }
}

/**
 * 毕业阈值测试主函数
 */
async function runGraduationTest() {
  console.log('\n🎯 开始毕业阈值测试');
  console.log(`📝 创建者钱包: ${CREATOR_WALLET}`);
  console.log(`📝 购买者钱包: ${BUYER_WALLET}`);
  console.log('='.repeat(60));
  
  // 1. 尝试加载指定的钱包
  console.log(`\n🔑 尝试加载指定钱包...`);
  const creatorKeypair = loadWalletByAddress(CREATOR_WALLET);
  const buyerKeypair = loadWalletByAddress(BUYER_WALLET);
  
  console.log(`\n📍 使用的钱包:`);
  console.log(`   创建者: ${creatorKeypair.publicKey.toString()}`);
  console.log(`   购买者: ${buyerKeypair.publicKey.toString()}`);
  
  const isUsingTargetCreator = creatorKeypair.publicKey.toString() === CREATOR_WALLET;
  const isUsingTargetBuyer = buyerKeypair.publicKey.toString() === BUYER_WALLET;
  
  if (isUsingTargetCreator && isUsingTargetBuyer) {
    console.log(`✅ 使用指定的目标钱包`);
  } else {
    console.log(`⚠️  未能加载指定钱包，使用替代钱包:`);
    if (!isUsingTargetCreator) console.log(`   ❌ 创建者钱包不匹配`);
    if (!isUsingTargetBuyer) console.log(`   ❌ 购买者钱包不匹配`);
  }
  
  // 2. 检查初始余额
  console.log(`\n💰 检查初始余额:`);
  await checkWalletBalance(creatorKeypair.publicKey.toString(), '创建者');
  await checkWalletBalance(buyerKeypair.publicKey.toString(), '购买者');
  
  // 3. 检查工厂合约状态
  console.log(`\n🏭 检查工厂合约状态...`);
  try {
    const factoryResponse = await axios.post(`${BACKEND_API}/bonding-curve/initialize-factory`, {});
    
    if (factoryResponse.data.success) {
      console.log(`✅ 工厂合约状态: ${factoryResponse.data.data.message}`);
    } else {
      console.log(`⚠️  工厂合约问题: ${factoryResponse.data.error}`);
    }
  } catch (error) {
    console.log(`❌ 工厂合约检查失败: ${error.message}`);
    return;
  }
  
  // 4. 创建代币
  console.log(`\n🪙 创建代币...`);
  const tokenConfig = {
    name: 'Graduation Test Token',
    symbol: 'GTT',
    uri: 'https://example.com/gtt-metadata.json'
  };
  
  const tokenResult = await createTokenViaAPI(creatorKeypair, tokenConfig);
  if (!tokenResult) {
    console.error('❌ 代币创建失败，终止测试');
    return;
  }
  
  const tokenMint = tokenResult.mint;
  console.log(`🎉 代币创建成功！地址: ${tokenMint}`);
  
  // 等待一段时间让交易确认
  console.log(`⏳ 等待交易确认...`);
  await new Promise(resolve => setTimeout(resolve, 5000));
  
  // 5. 获取初始代币信息
  console.log(`\n📊 获取代币初始信息...`);
  let tokenInfo = await getTokenInfo(tokenMint);
  if (tokenInfo) {
    console.log(`   总供应量: ${tokenInfo.totalSupply || '未知'}`);
    console.log(`   SOL储备: ${tokenInfo.solReserves || 0} lamports`);
    console.log(`   代币储备: ${tokenInfo.tokenReserves || 0}`);
    console.log(`   是否毕业: ${tokenInfo.isGraduated || false}`);
    console.log(`   市值: ${tokenInfo.marketCap || 0} SOL`);
  }
  
  // 6. 获取初始价格
  console.log(`\n💲 获取初始价格...`);
  let priceInfo = await getTokenPrice(tokenMint);
  if (priceInfo) {
    console.log(`   当前价格: ${priceInfo.price || 0} SOL/代币`);
    console.log(`   市值: ${priceInfo.marketCap || 0} SOL`);
  }
  
  // 7. 开始多次购买测试联合曲线
  console.log(`\n🛒 开始多次购买测试 - 目标: 3 SOL毕业阈值`);
  console.log('='.repeat(60));
  
  const purchaseAmounts = [0.1, 0.2, 0.3, 0.5, 0.7, 1.0, 0.2,0.2]; // 总计3.0 SOL
  let totalSpent = 0;
  let purchaseCount = 0;
  
  for (const amount of purchaseAmounts) {
    purchaseCount++;
    totalSpent += amount;
    
    console.log(`\n🔄 第 ${purchaseCount} 次购买:`);
    console.log(`   本次购买: ${amount} SOL`);
    console.log(`   累计购买: ${totalSpent.toFixed(1)} SOL`);
    
    // 购买前获取价格
    const preBuyPrice = await getTokenPrice(tokenMint);
    if (preBuyPrice) {
      console.log(`   购买前价格: ${preBuyPrice.price || 0} SOL/代币`);
      console.log(`   购买前市值: ${preBuyPrice.marketCap || 0} SOL`);
    }
    
    // 执行购买
    const buyResult = await buyTokens(tokenMint, buyerKeypair, amount);
    
    if (buyResult) {
      // 等待交易确认
      await new Promise(resolve => setTimeout(resolve, 3000));
      
      // 购买后获取价格
      const postBuyPrice = await getTokenPrice(tokenMint);
      if (postBuyPrice) {
        console.log(`   购买后价格: ${postBuyPrice.price || 0} SOL/代币`);
        console.log(`   购买后市值: ${postBuyPrice.marketCap || 0} SOL`);
        
        if (preBuyPrice && preBuyPrice.price > 0) {
          const priceIncrease = ((postBuyPrice.price - preBuyPrice.price) / preBuyPrice.price * 100);
          console.log(`   📈 价格涨幅: ${priceIncrease.toFixed(2)}%`);
        }
      }
      
      // 检查是否已毕业
      const updatedTokenInfo = await getTokenInfo(tokenMint);
      if (updatedTokenInfo) {
        console.log(`   SOL储备: ${(updatedTokenInfo.solReserves || 0) / LAMPORTS_PER_SOL} SOL`);
        console.log(`   是否毕业: ${updatedTokenInfo.isGraduated || false}`);
        
        if (updatedTokenInfo.isGraduated) {
          console.log(`\n🎓 代币已毕业！`);
          console.log(`   毕业时间: ${updatedTokenInfo.graduatedAt || '未知'}`);
          console.log(`   触发阈值: 3 SOL`);
          console.log(`   实际储备: ${(updatedTokenInfo.solReserves || 0) / LAMPORTS_PER_SOL} SOL`);
          break;
        }
      }
      
      console.log(`   ✅ 第 ${purchaseCount} 次购买完成`);
    } else {
      console.log(`   ❌ 第 ${purchaseCount} 次购买失败`);
    }
    
    // 如果接近毕业阈值，缩短等待时间
    if (totalSpent >= 2.5) {
      await new Promise(resolve => setTimeout(resolve, 2000));
    } else {
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }
  
  // 8. 最终统计
  console.log(`\n📊 最终统计报告:`);
  console.log('='.repeat(60));
  console.log(`   总购买次数: ${purchaseCount}`);
  console.log(`   总花费: ${totalSpent.toFixed(1)} SOL`);
  
  const finalTokenInfo = await getTokenInfo(tokenMint);
  const finalPrice = await getTokenPrice(tokenMint);
  
  if (finalTokenInfo) {
    console.log(`   最终SOL储备: ${(finalTokenInfo.solReserves || 0) / LAMPORTS_PER_SOL} SOL`);
    console.log(`   是否已毕业: ${finalTokenInfo.isGraduated || false}`);
    console.log(`   最终市值: ${finalTokenInfo.marketCap || 0} SOL`);
  }
  
  if (finalPrice) {
    console.log(`   最终价格: ${finalPrice.price || 0} SOL/代币`);
  }
  
  // 9. 分析3 SOL的分配
  console.log(`\n💰 3 SOL 分配分析:`);
  console.log('='.repeat(60));
  
  if (finalTokenInfo && finalTokenInfo.isGraduated) {
    const totalReserves = (finalTokenInfo.solReserves || 0) / LAMPORTS_PER_SOL;
    
    // 根据智能合约逻辑分析分配
    // 通常联合曲线会有以下分配：
    // - 大部分用于流动性池
    // - 一部分给创建者
    // - 一部分给平台
    
    console.log(`   总储备池: ${totalReserves.toFixed(4)} SOL`);
    console.log(`   创建者分配 (估算): ${(totalReserves * 0.1).toFixed(4)} SOL (10%)`);
    console.log(`   平台费用 (估算): ${(totalReserves * 0.05).toFixed(4)} SOL (5%)`);
    console.log(`   流动性池 (估算): ${(totalReserves * 0.85).toFixed(4)} SOL (85%)`);
    
    console.log(`\n🎯 创建者钱包 ${CREATOR_WALLET.slice(0, 8)}... 预计获得:`);
    console.log(`   📈 ${(totalReserves * 0.1).toFixed(4)} SOL (按10%计算)`);
  } else {
    console.log(`   ⚠️  代币尚未毕业，无法计算最终分配`);
    console.log(`   当前储备: ${finalTokenInfo ? (finalTokenInfo.solReserves || 0) / LAMPORTS_PER_SOL : 0} SOL`);
    console.log(`   需要达到: 3.0 SOL`);
  }
  
  console.log(`\n🏁 毕业阈值测试完成！`);
  console.log(`📄 详细信息请查看后端日志以了解毕业事件通知`);
}

// 错误处理和主函数执行
process.on('unhandledRejection', (error) => {
  console.error('未处理的Promise拒绝:', error);
  process.exit(1);
});

if (require.main === module) {
  runGraduationTest().catch(console.error);
}

module.exports = {
  runGraduationTest,
  createTokenViaAPI,
  buyTokens,
  getTokenPrice,
  getTokenInfo
};